<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/2
 * Time: 13:58
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysGrade;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;

class GradeController extends ControllerBase
{


    /**
     * 检查类型
     * @param $type
     * @param string $operater
     * @return bool
     * create by dale 20180327
     */
    public function checkPower($type,$operater=''){
        if($type == 1){
            $tag = 'Coop_Agency';
        }else if($type == 2){
            $tag = 'Coop_Supply';
        }
        if($operater != ''){
            $tag .= '_'.ucfirst($operater); //首字母大写
        }
        return UserPower::checkUserPower($tag);
    }

    /**
     * 
     * create by xjq 20180602
     */
    public function indexAction(){
        $this->view->pick('grade/index');
    }


    public function gradeListAction(){
        $type = $this->request->getQuery('type' , 'int');
        Assets::easyUI();
        Assets::importJs('js/grade/gradeList.js');
        $this->view->pick('grade/gradeList');
        Template::exists('Grade_Info', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
//        if($this->checkPower($type,'add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
//        }
//        if($this->checkPower($type,'del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
//        }
        if (in_array($type , [1 , 2])) { //1，案例 2.周报
            $month = $this->db->fetchAll("select sMonth from XHSys_Grade where bDelete = 0 and iType = {$type} group by sMonth ");
            $month = array_column($month , 'sMonth','sMonth');
            $month[''] = '请选择日期';
            $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_month', 'data'=>$month,'default'=>'','style'=> 'width:100px;');
            $schools = User::getSchoolPower(true);
            $schools[''] = '请选择学校';
            $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_school', 'data'=>$schools,'default'=>'','style'=> 'width:180px;');

        }
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'Grade_Info', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }


    /**
     * 获取列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180602
     */
    public function getListAction(){
        $type = $this->request->getPost('type','string');
        $key  = $this->request->getPost('key','string');
        $schoolId = $this->request->getPost('schoolId' , 'string');
        $sort = $this->request->getPost('sort','string');
        $order = $this->request->getPost('order', 'string');
        $month = $this->request->getPost('month' , 'string');
        $builder = $this->modelsManager->createBuilder()
            ->from(['g' => 'Admin\\Models\\sys\\XhsysGrade' ])
            ->where('g.bDelete = 0');
        if ($type) {
            $builder->andWhere(' g.iType = :iType: ' , [ 'iType' => $type ]);
        }
        if (in_array($type , [1 , 2])) { //1，案例 2.周报
            $builder->leftJoin('Admin\\Models\\school\\XhschoolInfo','g.iTargetId = i.iSchoolId','i')
                ->columns(['g.iRecId','g.iTargetId','g.sMonth','g.iGrade','g.mDesc','g.tCreateDate',
                          'g.iCreateUserId','g.tLastModifyDate','g.iLastModifyUserId','g.iType','i.sSchoolName']);
            if ($key) {
                $builder->andWhere('i.sSchoolName like :key: or g.iTargetId like :key: ' , [ 'key' => $key ]);
            }
            if ($schoolId) {
                $builder->andWhere('g.iTargetId = :schoolId: ' , [ 'schoolId' => $schoolId ]);
            }
            if ($month) {
                $builder->andWhere('g.sMonth = :month: ' ,['month' => $month] );
            }
            if ($sort && $order) {
                $sort = $sort == 'sSchoolName' ? 'iTargetId' : $sort;
                $builder->orderBy( " g.{$sort}  $order ");
            }
            $data = Main::runBuilderPage($builder);
            Main::runUserNameById($data['rows'] , ['iCreateUserId' => 'iCreateUserId' , 'iLastModifyUserId' => 'iLastModifyUserId'],true);
            return $this->sendJsonResponse($data);
        } else {
            return $this->sendErrorResponse(400,'未知类型');
        }
    }

    /**
     * 成绩列表
     *
     * create by xjq 20180602
     */
    public function gradeFormAction(){
        $this->view->pick('grade/gradeForm');
        Assets::select2();
        Assets::importJs('js/grade/gradeForm.js');
        $this->view->setVar('schools' , User::getSchoolPower(true));
        $id = $this->request->getQuery('iRecId');
        if ($id) {
            $info = XhsysGrade::findFirst($id)->toArray();
            if (!User::isAdmin() && $info['iCreateUserId'] != Main::getLoginUserInfo('userId')) {
                return $this->sendViewError('没有权限');
            }
            $this->view->setVar('info',$info);
        }
    }

    /**
     * 删除成绩
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180602
     */
    public function delGradeAction(){
        try{
            $iRecId = $this->request->getPost('id' , 'int');
            $obj = XhsysGrade::findFirst($iRecId);
            if (!User::isAdmin() && Main::getLoginUserInfo('userId') != $obj->iCreateUserId ) {
                return $this->sendErrorResponse(401 , '没有权限');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            return $this->sendSuccessResponse('删除成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 ,$e->getMessage());
        }
    }

    /**
     * 保存成绩
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180602
     */
    public function saveGradeAction(){
        $postData = $this->request->getPost();
        if (isset($postData['iRecId']) && $postData['iRecId']) {
            $obj = XhsysGrade::findFirst($postData['iRecId']);
        }else{
            $obj = XhsysGrade::findFirst([
                'conditions' => 'bDelete = 0  and iTargetId = :iTargetId:  and sMonth = :sMonth:  and iType = :iType: ',
                'bind'       => [ 'iTargetId' => $postData['iTargetId'], 'sMonth' => $postData['sMonth'] ,'iType' => $postData['iType']],
            ]);
            if (!$obj ) {
                $obj = new XhsysGrade();
            }else{
                return $this->sendErrorResponse(500 , '当月成绩已经生成请勿重复生成');
            }
        }
        $obj->assign($postData);
        if (!$obj->save()) {
            return $this->sendErrorResponse(500 , '保存失败');
        }
        return $this->sendSuccessResponse('保存成功');
    }



}